<template>
  <PageWrapDrawer :show="show" :isUpdate="true" 
  @success="onSubmit" 
  @on-drawer-close="onClose">
    <Form name="basic"
          :model="insideData.data"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          autocomplete="off"
          layout="horizontal">
      <FormItem label="角色名称" name="name" v-bind="validateInfos['data.name']">
        <a-input v-model:value="insideData.data.name"/>
      </FormItem>

      <FormItem label="备注" name="memo">
        <a-input v-model:value="insideData.data.memo"/>
      </FormItem>
    </Form>
  </PageWrapDrawer>
</template>
<script lang="ts" name="roleDrawer" setup>
import {computed, reactive, ref, toRaw, toRefs, watch} from 'vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {PageWrapDrawer} from '/@/components/PageWrapDrawer'
import {create, update} from '/@/api/admin/role';
import {
  Form,
  FormItem,
} from 'ant-design-vue';


// https://blog.csdn.net/qq_49327308/article/details/124467691
const {createMessage,} = useMessage();
const {info, success, warning, error} = createMessage;

const emit = defineEmits(['on-success', 'on-drawer-close'])
const props = defineProps({
    show: Boolean,
    isUpdate: Boolean,
    row: {type: [Object, null] as PropType<Object | null>, default: null,},
})

const useForm = Form.useForm;
const insideData = reactive({
      data: {
        id: null,
        name: '',
        memo: '',
      }
    });

watch(() => props.row, (v1, _) => {
  if (v1) {
    insideData.data.id = v1.id || null
    insideData.data.name = v1.name
    insideData.data.memo = v1.memo
  }
})

const rulesRef = reactive({
  'data.name': [
    {required: true, message: '请输入名称',},
  ],
});
const {resetFields, validate, validateInfos} = useForm(insideData, rulesRef, {
  onValidate: (...args) => {
    // console.log('args=>', ...args)
  },
});

const onSubmit = () => {
  validate()
    .then(async () => {
      let data = toRaw(insideData.data)
      if (props.isUpdate) {
        await update(data).then(() => {
          onClose()
        })
      } else {
        await create(data).then(() => {
          onClose()
        })
      }
      emit('on-success')
    }).catch(err => {
    console.log('error-----', err);
  });
}

const onClose = () => {
  Object.assign(insideData, {data: {}});
  resetFields();
  emit('on-drawer-close');
};

</script>
